package service

import (
	"amin-ease/globals"
	"amin-ease/internal/dao"
	"amin-ease/internal/dto"
	"amin-ease/internal/models"
	"amin-ease/pkg"
	"amin-ease/pkg/rabbitMQ"
	"encoding/json"
	"errors"
	"gorm.io/gorm"
	"log"
	"strconv"
	"time"
)

type UserServiceImpl interface {
	Register(req dto.RegisterReq) (resp *dto.RegisterResp, err error)
	UserList(req dto.ListReq) (resp *dto.ListResp, err error)
	FindUser(req dto.UsersReq) (resp *dto.UsersResp, err error)
	Add(req dto.AddReq) (resp *dto.AddResp, err error)
}
type UserService struct {
	md5 *pkg.Md5
}

func NewUserService() *UserService {
	return &UserService{
		pkg.NewMd5(),
	}
}
func (u *UserService) Register(req dto.RegisterReq) (resp *dto.RegisterResp, err error) {
	userDao := dao.NewUserDao()
	data, err := userDao.FindByUsername(req)
	if data.ID != 0 {
		return nil, errors.New("用户已存在")
	}
	user := &models.User{
		Model:    gorm.Model{},
		Username: req.Username,
		Password: pkg.NewMd5().Md5Str(req.Password),
	}
	register, err := userDao.Register(user)
	if err != nil {
		return nil, err
	}
	handler, err := pkg.NewJwt().TokenHandler(strconv.Itoa(int(register.ID)))
	if err != nil {
		return nil, err
	}
	return &dto.RegisterResp{Token: handler}, nil
}
func (u *UserService) UserList(req dto.ListReq) (resp *dto.ListResp, err error) {
	userDao := dao.NewUserDao()
	list, err := userDao.UserList(req)
	if err != nil {
		return
	}
	result, _ := globals.Rdb.Get(globals.Ctx, "list").Result()
	if result == "" {
		m, _ := json.Marshal(list)
		globals.Rdb.Set(globals.Ctx, "list", m, time.Hour*24)
	} else {
		json.Unmarshal([]byte(result), &list)
	}
	return &dto.ListResp{
		List: list,
	}, nil
}
func (u *UserService) FindUser(req dto.UsersReq) (resp *dto.UsersResp, err error) {
	userDao := dao.NewUserDao()
	user, err := userDao.FindUser(req)
	if err != nil {
		return nil, err
	}
	Rabbitmq := rabbitMQ.NewRabbitMQSimple("im_save_message")
	msgs := Rabbitmq.ConsumeSimple()
	forever := make(chan bool)
	//启用协程处理消息
	go func() {
		for d := range msgs {
			//消息逻辑处理，可以自行设计逻辑
			log.Printf("Received a message: %s", d.Body)

		}
	}()

	log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
	<-forever
	return &dto.UsersResp{
		Users: user,
	}, nil
}
func (u *UserService) Add(req dto.AddReq) (resp *dto.AddResp, err error) {
	userDao := dao.NewUserDao()
	person := &models.Ping{
		Model:   gorm.Model{},
		UserId:  req.UserId,
		Content: req.Content,
	}
	add, err := userDao.Add(person)
	if err != nil {
		return nil, err
	}
	Rabbitmq := rabbitMQ.NewRabbitMQSimple("im_save_message")
	m := map[string]interface{}{
		"userId":  req.UserId,
		"content": req.Content,
	}
	marshal, _ := json.Marshal(m)
	Rabbitmq.PublishSimple(string(marshal))
	return &dto.AddResp{
		Ping: add,
	}, nil

}
